'use client';

import type {
  IChildReply,
  IComment,
  IPagination,
  IParentReply,
  IPost,
  IReply,
} from '@/interfaces';
import { IQueryParams } from '@/interfaces';
import { queryAllPost, searchPost } from '@/services/api';
import { type ChangeEvent, useContext, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import classNames from 'classnames';
import { useSearchParams } from 'next/navigation';
import Alert from '@/app/[locale]/alert/alert';
import AlertLoad from '@/app/[locale]/alert/load';
import useToast from '@/hooks/useToast';
import { ReplyAdminContext } from '@/contexts/admin/forum/reply';
import CommentsReplyAdminPage from '@/app/[locale]/admin/forum/reply/comments';
import RepliesReplyAdminPage from '@/app/[locale]/admin/forum/reply/replies';
import ParentReplyReplyAdminPage from '@/app/[locale]/admin/forum/reply/parent';
import ChildReplyReplyAdminPage from '@/app/[locale]/admin/forum/reply/child';
import PostName from '@/app/[locale]/common/post/name';

export default function PostsReplyAdminPage(this: any) {
  const { show } = useToast();
  const urlSearchParams = useSearchParams();
  const [searchName, setSearchName] = useState('');
  const [params, setParams] = useState<IQueryParams>({
    page: 0,
    sectionId: urlSearchParams?.has('sid')
      ? parseInt(urlSearchParams.get('sid') + '')
      : undefined,
  });
  const [currentItemId, setCurrentItemId] = useState<number>();
  const context = useContext(ReplyAdminContext);
  const [detailItem, setDetailItem] = useState<IPost>();
  const [commentItem, setCommentItem] = useState<IComment>();
  const [replyItem, setReplyItem] = useState<IReply>();
  const [parentReplyItem, setParentReplyItem] = useState<IParentReply>();
  const [childReplyItem, setChildReplyItem] = useState<IChildReply>();

  const queryAllPostQuery = useQuery(
    ['/forum', '/posts', params, searchName],
    async (context) => {
      if (searchName) {
        return (await searchPost({
          query: {
            ...(context.queryKey[2] as any),
            name: context.queryKey[3],
          },
        })) as IPagination<IPost>;
      } else {
        return (await queryAllPost({
          query: context.queryKey[2] as any,
        })) as IPagination<IPost>;
      }
    },
    {
      keepPreviousData: true,
    },
  );

  function onChangeSearch(e: ChangeEvent<HTMLInputElement>) {
    const value = e.target.value.trim();
    setSearchName(value.toLowerCase());
  }

  function onClickPrevious() {
    const data = queryAllPostQuery.data;
    if (!data) {
      show({
        type: 'DANGER',
        message: '数据不存在',
      });
      return;
    }

    const page = Math.max(0, data.pageable.page - 1);
    setParams({ ...params, page });
  }

  function onClickNext() {
    const data = queryAllPostQuery.data;
    if (!data) {
      show({
        type: 'DANGER',
        message: '数据不存在',
      });
      return;
    }

    const page = Math.min(data.pageable.pages, data.pageable.page + 1);
    setParams({ ...params, page });
  }

  function onClickDetail(item: IPost) {
    setDetailItem(item);
    setCurrentItemId(item.id);
  }

  if (queryAllPostQuery.data) {
    const data = queryAllPostQuery.data;

    return (
      <ReplyAdminContext.Provider
        value={{
          ...context,
          detailItem,
          commentItem,
          setCommentItem,
          replyItem,
          setReplyItem,
          parentReplyItem,
          setParentReplyItem,
          childReplyItem,
          setChildReplyItem,
        }}
      >
        <div className="row">
          <div className="col">
            <div className="row">
              <div className="col">
                <div className="card">
                  <div className="card-header bg-transparent">
                    <div className="row row-cols-auto justify-content-between g-2">
                      <div className="col w-100">
                        <div className="input-group">
                          <span className="input-group-text">
                            <i className="bi bi-search"></i>
                          </span>
                          <input
                            onChange={onChangeSearch}
                            type="search"
                            className="form-control"
                            placeholder="搜索帖子"
                          />
                        </div>
                      </div>
                    </div>
                  </div>
                  <div className="card-body">
                    <div className="table-responsive">
                      <table className="table table-hover align-middle">
                        <thead>
                          <tr className="text-nowrap">
                            <th scope="col" className="w-10">
                              ID
                            </th>
                            <th scope="col" className="w-10">
                              名称
                            </th>
                          </tr>
                        </thead>
                        <tbody>
                          {data.content.map((item) => {
                            const style = (item.styles || []).find(
                              (value) => value.type === 'NAME',
                            );

                            return (
                              <tr
                                key={item.id}
                                onClick={onClickDetail.bind(this, item)}
                                className={classNames(
                                  'text-nowrap cursor-pointer',
                                  {
                                    'table-active': currentItemId === item.id,
                                  },
                                )}
                              >
                                <td>{item.id}</td>
                                <td className="text-truncate">
                                  <PostName
                                    item={item}
                                    isTable
                                    isFwSemibold={false}
                                  />
                                </td>
                              </tr>
                            );
                          })}
                        </tbody>
                      </table>
                    </div>

                    {data.content.length === 0 && <Alert message="暂无帖子" />}

                    <div className="my-4">
                      <nav aria-label="帖子分页">
                        <ul className="pagination justify-content-end">
                          <li
                            className={classNames(
                              'page-item',
                              data.pageable.previous ? false : 'disabled',
                            )}
                          >
                            <a
                              onClick={onClickPrevious}
                              className="page-link cursor-pointer"
                            >
                              上一页
                            </a>
                          </li>
                          <li
                            className={classNames(
                              'page-item',
                              data.pageable.next ? false : 'disabled',
                            )}
                          >
                            <a
                              onClick={onClickNext}
                              className="page-link cursor-pointer"
                            >
                              下一页
                            </a>
                          </li>
                        </ul>
                      </nav>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div className="row">
          {currentItemId && (
            <div className="col">
              <CommentsReplyAdminPage />
            </div>
          )}

          {commentItem && (
            <div className="col">
              <RepliesReplyAdminPage />
            </div>
          )}

          {replyItem && (
            <div className="col">
              <ParentReplyReplyAdminPage />
            </div>
          )}

          {parentReplyItem && (
            <div className="col">
              <ChildReplyReplyAdminPage />
            </div>
          )}
        </div>
      </ReplyAdminContext.Provider>
    );
  }

  if (queryAllPostQuery.error) {
    return <Alert message={queryAllPostQuery.error} type="error" />;
  }

  return <AlertLoad />;
}
